import base64
import pickle
from django_redis import get_redis_connection
import json
from django import http
from django.shortcuts import render
from django.views.generic import View

from goods.models import SKU
from meiduo_mall.utils.constants import Code


class CartsView(View):

    def post(self, request):
        # 获取参数
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected', True)

        # 校验参数
        if not all([sku_id, count]):
            return http.JsonResponse({'error_msg': '参数不全'}, status=400)

        # count转整数
        try:
            count = int(count)
        except:
            return http.JsonResponse({'error_msg': '参数错误'}, status=400)

        # 是否存在sku_id
        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return http.JsonResponse({'error_msg': '参数错误'}, status=400)

        if count > sku.stock:
            return http.JsonResponse({'error_msg': '超出库存'}, status=400)

        user = request.user

        # user已登录
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            # hincrby(key,field,value) redis hash表命令
            redis_conn.hincrby('cart_%d' % user.id, sku_id, count)
            if selected:
                redis_conn.sadd('selected_%d' % user.id, sku_id)
            return http.JsonResponse({'code': Code.OK})
        else:
            # user 未登录

            carts = request.COOKIES.get('cart')
            if carts:
                carts = pickle.loads(base64.b64decode(carts.encode()))
                if sku_id in carts:
                    count += carts[sku_id]['count']
            else:
                carts = {}

            carts[sku_id] = {
                'count': count,
                'selected': selected
            }

            carts_str = base64.b64encode(pickle.dumps(carts)).decode()
            rsp = http.JsonResponse({'code': Code.OK})
            rsp.set_cookie('cart', carts_str)

            return rsp

    def get(self, request):

        user = request.user
        # 判断用户是否已登录
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            key = 'cart_%d' % user.id
            sku_ids = redis_conn.hkeys(key)
            # 获取已选择商品
            sku_id_selecteds = redis_conn.smembers('selected_%d' % user.id)
            cart_skus = []
            for sku_id in sku_ids:
                count = redis_conn.hget(key, sku_id).decode()
                sku = SKU.objects.get(id=sku_id)
                cart_skus.append({
                    'id': sku.id,
                    'selected': str(sku_id in sku_id_selecteds),
                    'count': int(count),
                    'name': sku.name,
                    'price': str(sku.price),
                    'img': sku.default_image_url.url,
                    'amount': str(sku.price * int(count))
                })

        else:
            # 获取参数COOKIE
            data = request.COOKIES.get('cart')
            # 参数转换
            if not data:
                return render(request, 'cart.html', {'cart_skus': []})
            data = pickle.loads(base64.b64decode(data.encode()))
            cart_skus = []
            for sku_id, item in data.items():
                try:
                    sku = SKU.objects.get(id=sku_id)
                except:
                    return http.HttpResponseForbidden('参数有误')

                cart_skus.append({
                    'id': sku.id,
                    'selected': str(item['selected']),
                    'count': item['count'],
                    'name': sku.name,
                    'price': str(sku.price),
                    'img': sku.default_image_url.url,
                    'amount': str(sku.price * int(item['count']))
                })
        return render(request, 'cart.html', {'cart_skus': cart_skus})

    def put(self, request):
        # 获取参数
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected', True)

        # 校验参数
        if not all([sku_id, count]):
            return http.JsonResponse({'error_msg': '参数不全'}, status=400)
        try:
            sku = SKU.objects.get(id=sku_id)
        except:
            return http.JsonResponse({'error_msg': '商品不存在'}, status=400)

        try:
            count = int(count)
        except:
            return http.JsonResponse({'error_msg': '参数有误'}, status=400)

        if count > sku.stock:
            return http.JsonResponse({'error_msg': '库存不足'}, status=400)

        user = request.user
        # 数据入库
        if user.is_authenticated:
            # 连接redis
            redis_conn = get_redis_connection('carts')
            redis_conn.hset('cart_%d' % user.id, sku_id, count)
            if selected:
                redis_conn.sadd('selected_%d' % user.id, sku_id)
            else:
                redis_conn.srem('selected_%d' % user.id, sku_id)
            cart_sku = {
                'id': sku.id,
                'selected': selected,
                'count': int(count),
                'name': sku.name,
                'price': str(sku.price),
                'img': sku.default_image_url.url,
                'amount': str(sku.price * int(count))
            }
            return http.JsonResponse({'code': Code.OK, 'cart_sku': cart_sku})
        else:
            cookie_str = request.COOKIES.get('cart')
            cookie_dic = pickle.loads(base64.b64decode(cookie_str.encode()))
            cookie_dic[sku_id]['count'] = count
            cookie_dic[sku_id]['selected'] = selected
            cookie_str = base64.b64encode(pickle.dumps(cookie_dic)).decode()
            cart_sku = {
                'id': sku.id,
                'selected': str(selected),
                'count': int(count),
                'name': sku.name,
                'price': str(sku.price),
                'img': sku.default_image_url.url,
                'amount': str(sku.price * int(count))
            }
            rsp = http.JsonResponse({'code': Code.OK, 'cart_sku': cart_sku})
            rsp.set_cookie('cart', cookie_str)

            return rsp

        # 返回响应

    def delete(self, request):

        data = json.loads(request.body.decode())

        sku_id = data.get('sku_id')
        if not sku_id:
            return http.JsonResponse({'error_msg': '参数不全'}, status=400)

        user = request.user

        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            redis_conn.hdel('cart_%d' % user.id, sku_id)
            redis_conn.srem('selected_%d' % user.id, sku_id)
            rsp = http.JsonResponse({'code': Code.OK})

        else:
            cookie_dic = pickle.loads(base64.b64decode(request.COOKIES.get('cart').encode()))
            try:
                del cookie_dic[sku_id]
            except:
                return http.JsonResponse({'error_msg': '参数有误'}, status=400)
            cookie_str = base64.b64encode(pickle.dumps(cookie_dic)).decode()
            rsp = http.JsonResponse({'code': Code.OK})
            rsp.set_cookie('cart', cookie_str)

        return rsp


class CartsSelectedAllView(View):
    def put(self, request):
        user = request.user
        selected = json.loads(request.body.decode()).get('selected')

        if selected is None:
            return http.JsonResponse({'error_msg': '参数不全'}, status=400)

        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            sku_ids = redis_conn.hkeys('cart_%d' % user.id)
            if selected:
                redis_conn.sadd('selected_%d' % user.id, *sku_ids)
            else:
                redis_conn.srem('selected_%d' % user.id, *sku_ids)
            return http.JsonResponse({'code': Code.OK})
        else:
            cookie_dic = pickle.loads(base64.b64decode(request.COOKIES.get('cart').encode()))
            for item in cookie_dic.values():
                item['selected'] = selected

            rsp = http.JsonResponse({'code': Code.OK})
            cookie_str = base64.b64encode(pickle.dumps(cookie_dic)).decode()
            rsp.set_cookie('cart', cookie_str)
            return rsp


class CartsSimpleView(View):
    def get(self, request):

        user = request.user

        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            redis_skus = redis_conn.hgetall('cart_%d' % user.id)
            cart_skus = []
            for sku_id, count in redis_skus.items():
                sku = SKU.objects.get(id=sku_id)
                cart_skus.append({
                    'sku_id': sku.id,
                    'name': sku.name,
                    'count': int(count),
                    'img': sku.default_image_url.url
                })

        else:
            cookie_str = request.COOKIES.get('cart')
            if not cookie_str:
                return http.JsonResponse({'cart_skus': []})
            cookie_dic = pickle.loads(base64.b64decode(cookie_str.encode()))
            cart_skus = []
            for sku_id, item in cookie_dic:
                sku = SKU.objects.get(id=sku_id)
                cart_skus.append({
                    'sku_id': sku.id,
                    'name': sku.name,
                    'count': int(item['count']),
                    'img': sku.default_image_url.url
                })
        return http.JsonResponse({'cart_skus': cart_skus})
